using System.Collections.Generic;
using System.Linq;
using System.Web.Mvc;
using AutoMapper;
using VMWorkshop.Domain;

namespace VMWorkshop.Web.Controllers
{
    public class ProductsController : Controller
    {
        private IProductRepository _repository = null;

        public ProductsController(IProductRepository repository)
        {
            this._repository = repository;
        }

        public ProductsController() : this(new ProductRepository()) { }

        public ActionResult Index()
        {
            return List();
        }

        public ActionResult List()
        {
            var products = this._repository.GetAll();

            IList<ProductListView> list = Mapper.Map<IList<Product>, IList<ProductListView>>(products);

            if (Request.AcceptTypes.Contains(RequestHeaders.Json))
            {
                return Json(list);
            }

            return View(list);
        }

        public ActionResult Edit(int id)
        {
            Product product = this._repository.GetProductById(id);
            ProductEditView edit = ProductEditView.ToProductEditView(product);

            if (Request.AcceptTypes.Contains(RequestHeaders.Json))
            {
                return Json(edit);
            }

            return View(edit);
        }

        [AcceptVerbs(HttpVerbs.Post)]
        public ActionResult Persist(ProductEditView edit)
        {
            Product newProduct = ProductEditView.ToProduct(edit);
            Product oldProduct = this._repository.GetProductById(newProduct.ProductId);
            oldProduct = Mapper.Map<Product, Product>(newProduct, oldProduct);

            this._repository.Persist(oldProduct);

            if (Request.AcceptTypes.Contains(RequestHeaders.Json))
            {
                return Json("success");
            }

            return RedirectToAction("List");
        }
    }
}
